import { useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'
import { reactive, toRefs } from 'vue'

import { authApi, currentUserApi, type ILoginReq, type IUserMenu } from '@/apis'
import { resetRouter } from '@/router'

import store, { useTabsStore } from '.'

export const useUserStore = defineStore('user', () => {
  const state = reactive({
    token: useStorage('token', ''),
    name: '',
    menus: [] as IUserMenu,
    roles: [] as string[],
    permissions: [] as string[],
    infoRequested: false
  })

  async function login(payload: ILoginReq) {
    const data = await authApi.login(payload)

    state.token = data
  }

  async function logout() {
    await authApi.logout()

    clear()
  }

  async function getInfo() {
    const data = await currentUserApi.getInfo()

    state.name = data.user.userName
    state.menus = data.menus
    state.roles = data.roles
    state.permissions = data.permissions
    state.infoRequested = true

    return {
      menus: state.menus,
      permissions: state.permissions
    }
  }

  async function clear() {
    if (!state.token) return

    const tabsStore = useTabsStore()

    state.token = ''
    state.name = ''
    state.roles = []
    state.permissions = []
    state.infoRequested = false

    await tabsStore.delAllTabs()
    resetRouter()
  }

  return {
    ...toRefs(state),
    login,
    logout,
    getInfo,
    clear
  }
})

export function useUserStoreHook() {
  return useUserStore(store)
}
